#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pika


# 建立到代理服务器的连接
credentials = pika.PlainCredentials('guest', 'guest')
conn_params = pika.ConnectionParameters('192.168.1.113', credentials=credentials, port=5672)
conn_broker = pika.BlockingConnection(conn_params)

# 获得信道
channel = conn_broker.channel()

# 声明交换器
channel.exchange_declare(exchange="hello-exchange",
                         type="direct",
                         passive=False,
                         durable=True,
                         auto_delete=False)

# 声明队列
# 通过键hola，将队列与交换器绑定起来
channel.queue_declare(queue="rabbit.queue.foo")
channel.queue_bind(queue="rabbit.queue.foo",
                   exchange="hello-exchange",
                   routing_key="hola")

# 处理传入消息函数
def msg_consumer(channel, method, header, body):
    # decode()把tytes变为str
    msg_body = body.decode()
    # 消息确认
    channel.basic_ack(delivery_tag=method.delivery_tag)
    if msg_body == "quit":
        # 停止消费并退出
        channel.basic_cancel(consumer_tag="hello-consumer")
        channel.stop_consuming()
    else:
        print(msg_body)
    return

# 订阅消费者
channel.basic_consume(msg_consumer,
                      queue="rabbit.queue.foo",
                      consumer_tag="hello-consumer")

# 开始消费
channel.start_consuming()




